import type { FormRules, FormItemRule, SelectOption } from 'naive-ui'
import { useAppsStore } from '@/stores/modules/app'
import type { sexType } from '@/types/app'
import { isEmail } from '@/utils/validate'
import loginApi from '@/service/api/login'
const validateEmail = (_: FormItemRule, value: string): boolean => {
  if (!value) return true
  return isEmail(value)
}
export interface ModelType {
  managerName: string | null
  remark: string | null
  email: string | null
  sex: sexType
}

export class BaseInfoModel {
  /**
   * 表单数据
   */
  private data: ModelType = {
    managerName: '楚芝馨',
    remark: '',
    email: '',
    sex: 0
  }
  /**
   * 表单字段的验证规则
   */
  private rules: FormRules = {
    managerName: [
      {
        required: true,
        message: '请输入昵称',
        trigger: 'blur'
      }
    ],
    sex: [
      {
        type: 'number',
        required: true,
        message: '请选择性别',
        trigger: 'blur'
      }
    ],
    email: [
      {
        validator: validateEmail,
        message: '邮箱格式不正确',
        trigger: 'blur'
      }
    ]
  }
  /**
   * 表单字段的验证规则
   */
  public sexOptions: SelectOption[] = [
    {
      label: '男',
      value: 1
    },
    {
      label: '女',
      value: 2
    },
    {
      label: '保密',
      value: 0
    }
  ]
  /**
   * 为特定字段添加额外的验证规则
   * @param key - 字段键
   * @param rule - 验证规则
   */
  public addRules(
    key: string,
    rule: FormRules | FormItemRule | FormItemRule[]
  ): void {
    this.rules[key] = rule
  }
  /**
   * 获取验证规则
   * @returns 验证规则
   */
  public getRules(): FormRules {
    return this.rules
  }

  /**
   * 获取表单数据
   * @returns 表单数据
   */
  public getData(): ModelType {
    const userStore = useAppsStore()
    this.data.managerName = userStore.userInfo?.managerName || null
    this.data.remark = userStore.userInfo?.remark || null
    this.data.sex = userStore.userInfo?.sex || 0
    this.data.email = userStore.userInfo?.email || null
    return this.data
  }

  public async save(data: ModelType) {
    const { code, message } = await loginApi.doUpdInfo(data)
    if (code !== 200) {
      throw message
    }
    const userStore = useAppsStore()
    const { doUserInfo } = userStore
    doUserInfo()
  }
}

export default new BaseInfoModel()
